package com.kfc.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import vo.User;

import com.kfc.dao.UserDao;
import com.kfc.util.DBUtil;

@Repository("sd")
public class UserDaoImpl implements UserDao {
	@Autowired(required=true)
	private DataSource ds;
	@Override
	public int addUser(User user) {
		Connection conn = null;
		int flag = 0;
		String sql = "insert into user(username,password,phonenum,address)values(?,?,?,?)";
		PreparedStatement ps = null;
		try {
			conn = ds.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getPhoneNum());
			ps.setString(4, user.getAddress());
			flag = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.free(conn, ps, null);
		}
		return flag;
	}

	@Override
	public User queryUser(String userName, String password) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from user where username=? and password=?";
		User user = null;

		try {
			conn = ds.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, userName);
			ps.setString(2, password);
			rs = ps.executeQuery();
			if (rs.next()) {
				user = new User();
				user.setUserId(rs.getInt("userid"));
				user.setUserName(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setPhoneNum(rs.getString("phonenum"));
				user.setAddress(rs.getString("address"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtil.free(conn, ps, rs);
		}

		return user;
	}

}
